package leetcode.editor.cn;

class MaximumBinaryTree {
    public static void main(String[] args) {
        Solution solution = new MaximumBinaryTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public TreeNode constructMaximumBinaryTree(int[] nums) {
            return traversal(nums, 0, nums.length);
        }

        /*public TreeNode traversal(int[] nums, int left, int right) {
            if (right - left < 1) {
                return null;
            }

            if (right - left == 1) {
                return new TreeNode(nums[left]);
            }

            // 获取最大值的索引
            int maxIndex = left;
            for (int i = left + 1; i < right; i++) {    // 一定注意起始和结束范围不是0到数组最后一位
                if (nums[i] > nums[maxIndex]) {
                    maxIndex = i;   // 不能加break，因为需要找到最大的值索引
                }
            }

            TreeNode root = new TreeNode(nums[maxIndex]);
            root.left = traversal(nums, left, maxIndex);
            root.right = traversal(nums, maxIndex + 1, right);

            return root;
        }*/

        public TreeNode traversal(int[] nums, int left, int right) {
            if (right - left <= 0) {
                return null;
            }

            if (right - left == 1) {
                return new TreeNode(nums[left]);
            }

            int max = 0, idx = left;
            for (int i = left; i < right; i++) {
                if (max < nums[i]) {
                    max = nums[i];
                    idx = i;
                }
            }

            TreeNode root = new TreeNode(max);
            root.left = traversal(nums, left, idx);
            root.right = traversal(nums, idx + 1, right);
            return root;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
